import type { AxiosError } from 'axios'
import { udpUserStore } from 'udp/store/user-store'
import { NButton, NotificationReactive } from 'naive-ui'
import * as config from '@/config/theme-overrides'
import { refreshToken } from './Unauthorized'
import { router } from 'udp/router'
import { h } from 'vue'

export const ERROR_STATUS = {
  400: '请求出现语法错误~',
  401: '用户未授权~',
  403: '服务器拒绝访问~',
  404: '请求的资源不存在~',
  405: '请求方法未允许~',
  408: '网络请求超时~',
  500: '服务器内部错误~',
  501: '服务器未实现请求功能~',
  502: '错误网关~',
  503: '服务不可用~',
  504: '网关超时~',
  505: 'http版本不支持该请求~'
}

type ErrorStatus = keyof typeof ERROR_STATUS

const errAction = {}

const HandleUnauthorized = (error: AxiosError, isErrorMsg?: boolean) => {
  const errorCode = error.response?.status as number
  if (errAction[errorCode]) {
    return Promise.reject(error)
  }
  const curRoute = router.currentRoute.value
  const userStore = udpUserStore()
  if (config.isUnauthorizedJumpToLoginPage) {
    if (curRoute.path !== '/login') {
      userStore.logoutToPage()
    }
  } else {
    errAction[errorCode] = true
    const notification = window['$notification']
    if (notification && curRoute.path !== '/login' && isErrorMsg) {
      let count = 10
      const content = (note: NotificationReactive) => {
        return [
          h(
            NButton,
            {
              text: true,
              type: 'primary',
              onClick: () => {
                userStore.logoutToPage()
                note.destroy()
              }
            },
            {
              default: () => '重新登录'
            }
          ),
          h('span', { style: 'margin-left:10px;font-size:12px' }, `倒计时${count}`)
        ]
      }
      const note = notification.error({
        content: 'Unauthorized',
        duration: 10000,
        action: () => content(note),
        meta: '鉴权失败,请重新登录！',
        onAfterEnter: () => {
          const minusCount = () => {
            count--
            note.action = () => content(note)
            if (count > 0 && errAction[errorCode]) {
              window.setTimeout(minusCount, 1000)
            } else if (count === 0) {
              userStore.logoutToPage()
              note.destroy()
            }
          }
          window.setTimeout(minusCount, 1000)
        },
        onAfterLeave: () => {
          errAction[errorCode] = false
        }
      })
    } else {
      setTimeout(() => {
        errAction[errorCode] = false
      }, 3000)
    }
  }
}

export function handleAxiosError(error: AxiosError, isErrorMsg?: boolean) {
  const errorCode = error.response?.status as number
  // if (errorCode === 401 && !error.config.url?.includes('/uaa/oauth/token')) {
  //   return refreshToken(error, () => HandleUnauthorized(error, isErrorMsg))
  // }
  if (isErrorMsg) {
    const notification = window['$notification']
    if (error.response) {
      const errorMessage = error.response.data.error_description
      if (errAction[errorCode]) {
        return Promise.reject(error)
      }
      errAction[errorCode] = true
      if (errorCode !== 401) {
        if (ERROR_STATUS[`${errorCode as ErrorStatus}`]) {
          notification.error({
            content: `${errorCode}`,
            meta: errorMessage || ERROR_STATUS[`${errorCode as ErrorStatus}`],
            duration: 10000,
            onAfterLeave: () => {
              errAction[errorCode] = false
            }
          })
        } else {
          notification.error({
            content: 'Error',
            meta: errorMessage || '请求错误~',
            duration: 10000,
            onAfterLeave: () => {
              errAction[errorCode] = false
            }
          })
        }
      }
    } else {
      if (error.message?.includes('timeout')) {
        if (errAction['timeout']) return
        errAction['timeout'] = true
        notification.error({
          content: 'Error',
          meta: '请求超时~',
          duration: 10000,
          onAfterLeave: () => {
            errAction['timeout'] = false
          }
        })
      } else if (!window.navigator.onLine || error.message === 'Network Error') {
        if (errAction['Network']) return
        errAction['Network'] = true
        notification.error({
          content: 'Error',
          meta: '网络不可用',
          duration: 10000,
          onAfterLeave: () => {
            errAction['Network'] = false
          }
        })
      }
    }
  }

  return Promise.reject(error)
}
